package com.exm.sql.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.exm.sql.model.vo.ResponseResult;
import com.exm.sql.repository.RecordRepository;
import com.exm.sql.util.DateUtil;
import com.exm.sql.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.exm.sql.model.Record;

import java.util.Date;
import java.util.List;

@Service
public class RecordService {

    @Autowired
    RecordRepository recordRepository;


    @Autowired
    UserUtil userUtil;

    public ResponseResult findAll() {
        String account = userUtil.getUserAccountInfoByToken();
        LambdaQueryWrapper<Record> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Record::getAccount,account);
        wrapper.orderByDesc(Record::getRecordTime);
        List<Record> list = recordRepository.list(wrapper);
        return ResponseResult.success(list);
    }

    public ResponseResult deleteById(Long id) {
        boolean b = recordRepository.removeById(id);
        if(b) {
            return ResponseResult.success();
        }else {
            return ResponseResult.error();
        }
    }

    public ResponseResult save(Record record) {
        String account = userUtil.getUserAccountInfoByToken();
        record.setAccount(account);


        LambdaQueryWrapper<Record> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Record::getAccount,account).orderByDesc(Record::getCreateTime)
                .eq(Record::getIsStart,true);
        List<Record> records = recordRepository.list(lambdaQueryWrapper);
        if (records!=null&& !records.isEmpty()) {
            Record lastRecord = records.getFirst();
            long offsetDay = DateUtil.calculateDaysBetween(lastRecord.getRecordTime(), record.getRecordTime());
            record.setOffsetDay(offsetDay);
        }


        boolean b = recordRepository.save(record);
        if(b) {return ResponseResult.success();}
        else {return ResponseResult.error();}
    }
}
